package com.inspire.ijc.agent.asminstru;

import com.inspire.ijc.agent.IjcAgent;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

/**
 * @author ：inspire
 * @date ：Created in 2023/4/18 10:11
 * @description：
 * @modified By：inspire
 * @version:
 */
public class IjcClassWriter extends ClassWriter {
    ClassLoader classLoader;

    public IjcClassWriter(ClassReader classReader, int flags,ClassLoader classLoader) {
        super(classReader, flags);
        this.classLoader=classLoader;
    }

    @Override
    protected String getCommonSuperClass(String type1, String type2) {

        if(IjcAgent.wmIncludes.matches(type1)||IjcAgent.wmIncludes.matches(type2)){
            System.out.println("biz:type1:"+type1+",type2:"+type2);
            return "java/lang/Object";
        }

        Class class1;
        try {
            class1 = Class.forName(type1.replace('/', '.'), false, classLoader);
        } catch (ClassNotFoundException var8) {
            throw new TypeNotPresentException(type1, var8);
        }

        Class class2;
        try {
            class2 = Class.forName(type2.replace('/', '.'), false, classLoader);
        } catch (ClassNotFoundException var7) {
            throw new TypeNotPresentException(type2, var7);
        }

        if (class1.isAssignableFrom(class2)) {
            return type1;
        } else if (class2.isAssignableFrom(class1)) {
            return type2;
        } else if (!class1.isInterface() && !class2.isInterface()) {
            do {
                class1 = class1.getSuperclass();
            } while(!class1.isAssignableFrom(class2));

            return class1.getName().replace('.', '/');
        } else {
            return "java/lang/Object";
        }
    }
}
